import os
import string
import ConfigParser
import logging
import json
import exceptions
import BaseHTTPServer
import traceback
import pickle
import cgi
import time
import copy
import MySQLdb
from pprint import pprint

class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    """Thread to reply ts's request"""

    def opendb(self):
        db=MySQLdb.connect(host='localhost', db='xdouban', user='root', passwd='justsoso123', use_unicode=True)
        db.set_character_set('utf8')
        return db

    def closedb(self, db):
        db.close()    

    def escape_string(self, query):
        return MySQLdb.escape_string(query.encode("utf-8"))

    def writeheaders(self, contentLen, isFound, res_format):
        if isFound:
            self.send_response(200)
        else:
            self.send_response(404)

        if res_format == 'text':
            self.send_header('Content-type', 'text/plain')
        elif res_format == 'json':
            self.send_header('Content-type', 'application/json')
        else:
            self.send_header('Content-type', 'text/plain')

        self.send_header('Content-Length', str(contentLen))
        self.send_header('Cache-Control','max-age=60')
        self.send_header('Connection','close')
        self.end_headers()

    def parse_header(self, reqStr):
        mapStrs = reqStr.split('&')
        mapHeaders = {}
        for keyValue in mapStrs:
            pair = keyValue.split('=')
            if (len(pair) != 2):
                continue
            key = pair[0].strip()
            mapHeaders[key] = pair[1].strip()
        return mapHeaders

    def parse_param(self, reqStr):
        mapStrs=reqStr.split('&')
        mapHeaders = {}
        for kv in mapStrs:
            pair = kv.split('=')
            if(len(pair) != 2):
                continue
            key=pair[0].strip()
            if key not in mapHeaders:
                mapHeaders[key]=[]
            mapHeaders[key].append(pair[1].strip())
        return mapHeaders
    
    def draw_aoc(self, endpoint, params):
        
        timestamp = self.get_timestamp(params)
        dbops = self.open_db()

        data = dbops.get_cookie_stat(timestamp)
        dbops.close()
        
        if data is None:
            return json.dumps({"time":None,"percentage:":{}})

        opted_out = float(data["ao_one_cnt"])/data["total_user"]
        ret={"time":data["ts"], "percentage":{"opted_into":1-opted_out, "opted_out":opted_out} }
        return json.dumps(ret)

    def list(self):
        db = self.opendb() 

        cursor = db.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute("select id,uid,href,cover from user_albums order by id asc limit 2000")
        albums = cursor.fetchall()
        
        self.closedb(db)

        return json.dumps(albums) 
        
    def set(self):
        headers = self.parse_header(self.params)
        params = self.parse_param(self.params)
               
        return chart_callback(endpoint,params)

    def do_GET(self):
        try:
            ret = ""
            format = "json"
            pos = self.path.find("?")
            if pos > 0:
                self.params = self.path[pos+1:]
                self.path = self.path[0:pos]

            if self.path.find("/set") != -1:
                ret = self.set()
            elif self.path.find("/list") != -1:
                ret = self.list()

            if len(ret) > 0:
                self.writeheaders(len(ret), True, format)
            else:    
                self.writeheaders(len(ret), False, "text")
            
            self.wfile.write(ret)
            self.wfile.close()
        except IOError:
            traceback.print_exc()
        except:
            traceback.print_exc()

def main():
    input_port = 8080 

    httpd = BaseHTTPServer.HTTPServer(('', input_port), RequestHandler)
    logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s')
    httpd.serve_forever()

if __name__ == '__main__':
    main()
